package com.blog.sys.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.blog.blog.controller.CommonController;
import com.blog.sys.dao.SysUserRepository;
import com.blog.sys.entity.SysUser;
import com.blog.common.exception.ParamRepetitionExcepion;
import com.blog.common.exception.UserStateUpdateException;
import com.blog.common.newclass.Result;
import com.blog.common.newclass.StrSource;
import com.blog.common.newclass.dostringabs.DoEntryFirst;
import com.blog.common.newclass.dostringabs.DoEntryLast;
import com.blog.common.newclass.dostringabs.DoEntryMind;
import com.blog.common.newclass.inteface.DoStr;
import com.blog.sys.service.SysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/user")
public class SysUserController extends CommonController {
    private final static Logger logger = LoggerFactory.getLogger(SysUserController.class);
    public static final String PERMISSIONS_USER_INFO_VIEW = "userInfo:view";
    public static final String PERMISSIONS_USER_INFO_ADD = "userInfo:add";
    public static final String PERMISSIONS_USER_INFO_DEL = "userInfo:lockUser";

    @Autowired
    private SysUserRepository sysUserRepository;

    @Autowired
    private SysUserService userService;

    /**
     * 触发MyShiroRealm.doGetAuthenticationInfo()实现登录
     *
     * @param request
     * @param mv
     * @return
     * @throws Exception
     */
    @RequestMapping("/list")
    @RequiresPermissions(PERMISSIONS_USER_INFO_VIEW)
    public ModelAndView list(HttpServletRequest request, ModelAndView mv) {
        mv.setViewName("/userInfo");
        return mv;
    }

    private List<SysUser> entryPassword(List<SysUser> all) throws Exception {
        List<SysUser> entryAll = new ArrayList<>();
        for (SysUser user :
                all) {
            if (StringUtils.isEmpty(user.getPassword()))
                continue;
            DoStr doStr = new StrSource(user.getPassword());
            doStr = new DoEntryMind(doStr);
            doStr = new DoEntryFirst(doStr);
            doStr = new DoEntryLast(doStr);
            user.setPassword(doStr.getStr());
            entryAll.add(user);
        }
        return entryAll;
    }

    /**
     * 触发MyShiroRealm.doGetAuthenticationInfo()实现登录
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/query", produces = "application/json;charset=UTF-8")
    @ResponseBody
    @RequiresPermissions(PERMISSIONS_USER_INFO_VIEW)
    public Result query(SysUser sysUser) {
        List<SysUser> all = sysUserRepository.findAll();
        List<SysUser> entryAll = null;
        try {
            entryAll = entryPassword(all);
        } catch (Exception e) {
            logger.error("find user list is error : " + e.getMessage());
        }
        long count = sysUserRepository.count();
        return page(entryAll, count);
    }


    @RequestMapping(value = "/add", produces = "application/json;charset=UTF-8")
    @ResponseBody
    @RequiresPermissions(PERMISSIONS_USER_INFO_ADD)
    public Result add(SysUser user, ModelAndView mv, String roleStr) throws Exception {
        user.setCreateTime(System.currentTimeMillis());
        user.setPassword(md5EntryPassword(user.getPassword()));
        logger.info("adduser = " + JSON.toJSONString(user) + ", roleStr = " + roleStr);
        user.setRoleList(roleStr);
        try {
            userService.save(user);
        } catch (ParamRepetitionExcepion paramRepetitionExcepion) {
            logger.debug(paramRepetitionExcepion.getLocalizedMessage());
            return warn(paramRepetitionExcepion.getLocalizedMessage());
        }
        return success("保存成功", user);
    }


    /**
     * 批量锁定账户
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/lockUser", produces = "application/json;charset=UTF-8")
    @ResponseBody
    @RequiresPermissions(PERMISSIONS_USER_INFO_DEL)
    public Result lockUser(String usersJson) {
        StringBuffer errMsg = new StringBuffer();
        List<String> lockSucIds = new ArrayList<>();
        List<SysUser> users = JSONArray.parseArray(usersJson, SysUser.class);
        for (SysUser sysUser :
                users) {
            try {
                userService.lockUser(sysUser.getId());
                lockSucIds.add(sysUser.getUsername());
            } catch (UserStateUpdateException e) {
                logger.debug(e.getLocalizedMessage());
                errMsg.append(e.getLocalizedMessage() + " ");
            }
            logger.debug("lock user success: {}", sysUser);
        }
        return success("成功锁定账户：" + ArrayUtils.toString(lockSucIds), null);
    }

    @RequestMapping(value = "/existsUsername", produces = "application/json;charset=UTF-8")
    @ResponseBody
    @RequiresPermissions(PERMISSIONS_USER_INFO_VIEW)
    public Result existsUsername(String username) {
        return success("查询成功", userService.existsUsername(username));
    }

}